import React from 'react'
import './App.css'
import TodoInput from './components/TodoInput'
import TodoList from './components/TodoList'
import FilterTabs from './components/FilterTabs'
import { BrowserRouter, Routes, Route, useLocation } from 'react-router-dom'
import { useSelector, useDispatch } from 'react-redux'
import type { RootState } from './store'
import {
  setInputValue,
  addTodo,
  editTodo,
  clearTodos,
} from './store/todoSlice'

// 主应用入口，包含路由、待办事项逻辑和状态管理

export type TodoStatus = 'all' | 'active' | 'completed'
export interface Todo {
  id: number
  text: string
  completed: boolean
}

// getFilterFromPath: 根据路由路径返回当前筛选状态
const getFilterFromPath = (pathname: string): TodoStatus => {
  if (pathname === '/active') return 'active'
  if (pathname === '/completed') return 'completed'
  if (pathname === '/all' || pathname === '/') return 'all'
  return 'all'
}

// TodoApp: 具体的待办事项应用组件，包含所有核心逻辑
const TodoApp: React.FC = () => {
  const dispatch = useDispatch()
  const editingId = useSelector((state: RootState) => state.todo.editingId)
  const inputValue = useSelector((state: RootState) => state.todo.inputValue)
  const location = useLocation()
  const filter = getFilterFromPath(location.pathname)

  // 新增或编辑
  const handleAddOrEdit = () => {
    if (editingId !== null) {
      dispatch(editTodo())
    } else {
      dispatch(addTodo())
    }
  }

  return (
    <div className="app-bg">
      <div className="todo-container">
        <TodoInput
          onAdd={handleAddOrEdit}
          value={inputValue}
          setValue={v => dispatch(setInputValue(v))}
          isEditing={editingId !== null}
        />
        <div className="todo-header">
          <FilterTabs value={filter} />
          <button className="clear-btn" onClick={() => dispatch(clearTodos())}>清空</button>
        </div>
        <TodoList filter={filter} />
      </div>
    </div>
  )
}

// App: 路由入口，支持 /、/all、/active、/completed
const App: React.FC = () => (
  <BrowserRouter>
    <Routes>
      <Route path="/" element={<TodoApp />} />
      <Route path="/all" element={<TodoApp />} />
      <Route path="/active" element={<TodoApp />} />
      <Route path="/completed" element={<TodoApp />} />
    </Routes>
  </BrowserRouter>
)

export default App
